<template>
  <div class="citySelect">
    <section>
      <span>{{prov}}</span>
      <select v-model="prov">
        <option v-for="option in arr" :value="option.name" :key="option.mane">{{ option.name }}</option>
      </select>
    </section>
    <section>
      <span>{{city}}</span>
      <select v-model="city">
        <option v-for="option in cityArr" :value="option.name" :key="option.mane">{{ option.name }}</option>
      </select>
    </section>
    <section>
      <span>{{district}}</span>
      <select v-model="district" v-if="district">
        <option
          v-for="option in districtArr"
          :value="option.name"
          :key="option.mane"
        >{{ option.name }}</option>
      </select>
    </section>
  </div>
</template>
<script>
import { arrAll } from "@/config/cityData";
export default {
  data() {
    return {
      arr: arrAll,
      prov: "北京",
      city: "北京",
      district: "东城区",
      cityArr: [],
      districtArr: []
    };
  },
  methods: {
    updateCity: function() {
      for (var i in this.arr) {
        var obj = this.arr[i];
        if (obj.name == this.prov) {
          this.cityArr = obj.sub;
          break;
        }
      }
      this.city = this.cityArr[1].name;
    },
    updateDistrict: function() {
      for (var i in this.cityArr) {
        var obj = this.cityArr[i];
        if (obj.name == this.city) {
          this.districtArr = obj.sub;
          break;
        }
      }
      if (
        this.districtArr &&
        this.districtArr.length > 0 &&
        this.districtArr[1].name
      ) {
        this.district = this.districtArr[1].name;
      } else {
        this.district = "";
      }
    }
  },
  beforeMount: function() {
    this.updateCity();
    this.updateDistrict();
  },
  watch: {
    prov: function() {
      this.updateCity();
      this.updateDistrict();
    },
    city: function() {
      this.updateDistrict();
    }
  }
};
</script>
 <style lang="scss" scoped>
.citySelect {
  overflow: hidden;

  width: 80%;
  margin: 10% auto;
  flex: 1;
  display: flex;
  text-align: center;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  font-size: 0.6rem;
  section {
    padding: 1rem;
    margin: 0.4rem;
    margin-top: 15%;
    overflow: hidden;
    padding: 2%;
    position: relative;
    border: 1px solid #ddd;
    border-radius: 0.2rem;
  }
  span {
    padding-right: 0.8rem;

    background-image: url(../assets/tri.png);
    background-size: 0.7rem 0.6rem;
    background-repeat: no-repeat;
    background-position: right center;
  }
  span::before {
    content: "";
    display: inline-block;
    width: 0;
    height: 0;
    border: 0.3rem;

    border-top-color: #ddd;
    border-left-color: #ddd;
    border-bottom-color: #0b7555;
    border-right-color: #ddd;
  }
  select {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    opacity: 0;
  }
}
</style>

